<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/15
 * Time: 21:02
 */

namespace app\index\controller;

use app\index\model\BySale;
use app\index\model\M;
use app\index\model\ProductInfo;
use app\index\model\RechargeMember;
use app\index\model\Sale as SaleModel;
use app\index\model\User;
use app\index\server\LoginRegServer;
use app\index\server\Message;
use app\index\server\MyselfServer;
use app\index\validate\MySelfValidate;
use app\model\CutDownModel;
use app\model\OrderModel;
use app\model\UserModel;
use think\cache\driver\Redis;
use think\Db;
use think\Request;
use think\Cookie;

class Myself extends Auth
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new M();
    }


    /**
     * @var 我的信息
     */
    public function message()
    {
        $server = new Message();
        $messgae = $server->getList($this->uid);
        $this->assign('messgae', $messgae);
        return $this->fetch('message');
    }


    /**
     * @var 已读
     */
    public function read_message()
    {
        $messgaeId = (int)input('parmam.msgid');
        if ($messgaeId > 0) {
            $server = new Message();
            $messgae = $server->getList("uid = {$this->uid} and is_read = 1 and id = {}", ['is_read' => 1]);
            $this->assign('messgae', $messgae);
            return $this->fetch('message');
        }
    }


    public function tix()
    {
        $myselfServer = new MyselfServer();
        $userInfo = $myselfServer->getTixInfo();
        // var_dump($userInfo);die;
        $this->assign('userInfo', $userInfo);
        return $this->fetch();
    }


    public function index()
    {

        if ($this->uid) {
            $myselfServer = new MyselfServer();
            $object = (new OrderModel($this->suffix));
            $num['ready'] = $object->countNum("id = {$this->uid} and ostate = '1'", 'id');
            $num['ing'] = $object->countNum("id = {$this->uid} and ostate = '2'", 'id');
            $num['ok'] = $object->countNum("id = {$this->uid} and ostate = '3'", 'id');
            $userInfo = $myselfServer->getUserInfo($this->uid);
            $this->assign('num', $num);
            $this->assign('userInfo', $userInfo);
            return $this->fetch();
        }
        $this->redirect('/login');
        exit;
    }

    // 个人详情
    public function info()
    {
        $myselfServer = new MyselfServer();
        $userInfo = $myselfServer->obtainUserInfo("id = {$this->uid}", 'username,surename,birthday,qq,email,mobile');
        $this->assign('userInfo', $userInfo);
        return $this->fetch();
    }

    /**
     * @var 下级
     */
    public function down()
    {
        // $limit = (int)input('param.limit');
        // if ($limit >= 0) {
        //     $myselfServer = new MyselfServer();
        //     $downInfo = $myselfServer->getSonInfo("p_id = {$this->uid}", $limit);
        //     return json_encode($downInfo);
        //     $this->assign('downInfo', $downInfo);
            return $this->fetch();
        // }
    }

    public function subUsers()
    {
        $myselfServer = new MyselfServer();
        $downInfo = $myselfServer->getSonInfo("p_id = {$this->uid}", 0);
        // dump($downInfo);die;
        // return $downInfo;
        return json_encode($downInfo);
    }

    public function update()
    {
        $params = (new MySelfValidate())->goCheck();
        $arr['surename'] = $params['surename'];
        $arr['birthday'] = $params['birthday'];
        $arr['qq'] = $params['qq'];
        $arr['email'] = $params['email'];
        $where = 'id = ' . session('Auth.Uid');
        $result = (new MyselfServer())->changeUserInfo($where, $arr);
        return $result;
    }

    // 帮助中心
    public function help()
    {
        return $this->fetch();
    }

    // 物流查询
    public function transportation()
    {
        return '物流查询';
    }

    // 售后服务
    public function afterSale()
    {
        return $this->fetch();
    }

    //优惠券
    public function Coupon()
    {
        //echo "<pre />";
        $uid = $this->uid;
        $info = $this->model->selectWhere('sy_coupon', 'uid', $uid);
        //var_dump($info);die;
        $this->assign('info', $info);
        return $this->fetch();
    }

    //优惠券赠送
    public function togive()
    {
        $uid = $this->model->find('sy_user', 'mobile', $_POST['phone'])['id'];
        if ($uid) {
            $data['uid'] = $uid;
            $result = $this->model->change('sy_coupon', $_POST['id'], $data);
            return $result;
        } else {
            return 'no';
        }
    }

    // 收货地址
    public function address()
    {
        $myselfServer = new MyselfServer();
        $addrInfo = $myselfServer->getAddress($this->uid);
        $this->assign('addrInfo', $addrInfo);
        return $this->fetch();
    }

    // 添加新收货地址
    public function insertAddress()
    {
        $myselfServer = new MyselfServer();
        $result = $myselfServer->insertAddress();
        return $result;
    }

    // 变更默认收货地址
    public function changeAddress()
    {
        $myselfServer = new MyselfServer();
        $result = $myselfServer->changeAddress();
        return $result;
    }

    // 地址详情
    public function detail()
    {
        $params = Request::instance()->param();
        $id = $params['id'];
        $myselfServer = new MyselfServer();
        $result = $myselfServer->detail($id);
        return $result;
    }

    public function editAddress()
    {
        $params = Request::instance()->param();
        $myselfServer = new MyselfServer();
        $result = $myselfServer->update($params);
        return $result;
    }

    public function delAddr($id)
    {
        $myselfServer = new MyselfServer();
        $result = $myselfServer->delAddress($id);
        return $result;
    }

    public function mycode()
    {
        $uid = session('Auth.Uid');
        if ($uid) {
            $username = (new UserModel())->getValue('id = ' . (int)$uid, 'username');
            //生成二维码
            $url = 'http://sy.58bjcf.com/login/' . session('Auth.Uid');
            $this->assign('qrcode', CreateQrCode($url, $username));
            $this->assign('myurl', $url);
            $this->assign('name', $username);
            return $this->fetch('mycode');
        }
    }


    public function member()
    {
        $user = $this->model->find('sy_user', 'id', $this->uid);
        $this->assign('user', $user);
        return $this->fetch('become_member');
    }


    public function become_member()
    {
        $uid = session('Auth.Uid');
        // 检测用无充值记录a
        $member = RechargeMember::where('uid', '=', $uid)
            ->find();
        $userInfo = User::where('id', $uid)
            ->find();
        if (!$member && $userInfo && $userInfo->is_vip == 0) {
            $orderNum = newOrderNum();
            $pay = new Pay();
            $result = $pay->getPreOrder($userInfo->openid, 99, $orderNum, 'call');
            (new Redis)->set($orderNum, $uid, 20 * 60);
            return $result;
        } else {
            return setMsg(0, '非常抱歉您已经充值成为了会员');
        }
    }

    /**
     * @var 立即购买
     */
    public function buy($gid)
    {
        $uid = $this->uid;
        if ($uid) {
            $myselfServer = new MyselfServer();
            $is_vip = $myselfServer->getValue("id  =  {$uid}", 'is_vip');
            $addrInfo = $myselfServer->getAddress($this->uid);
            $a = json_decode(json_encode($addrInfo), true);
            $goodsInfo = ProductInfo::with(['product'])->where("status = 1 and id = {$gid}")->find();
            $sale_id = $goodsInfo['product']['sale_id'] ? $goodsInfo['product']['sale_id'] : 0;
            $is_sale = '';

            if ($is_vip) {
                $goodsInfo['price'] = $goodsInfo['member_price'];
            }
            if ($sale_id) {
                $sale = SaleModel::where('id', $sale_id)
                    ->where('status', '=', 1)
                    ->find();
                // 查看已经购买的数量
                $num = BySale::where('uid', session('Auth.Uid'))
                    ->where('sale_id', $sale->id)
                    ->where('product_id', $goodsInfo->product_id)
                    ->where('is_pay', '=', 1)
                    ->sum('num');
                if ($num >= $sale->max) {
                    return setMsg(0, '非常抱歉 您已享受过该优惠 如有疑问 请联系客服');
                }
            }
            $address = isset($a[0]) ? $a[0] : '';
            $express = $this->model->select('sy_express');
            $Coupon = $this->model->selectWhere('sy_coupon', 'uid', $uid);
            $this->assign('address', $address);
            $this->assign('goodsInfo', $goodsInfo);
            $this->assign('Coupon', $Coupon);
            $this->assign('is_sale', $is_sale);
            $this->assign('is_vip', $is_vip);
            $this->assign('express', $express);
            return $this->fetch();
        }
    }


    /**
     * @var 会员回调
     */
    public function status_ok($gid)
    {
        $uid = $this->uid;
        $user_data = $this->model->find('sy_user', 'id', $uid);
        if ($uid) {
            $order_no = (new Redis)->get($gid);
            $edit['is_pay'] = 1;
            $this->model->linghuo('sy_recharge_member', "billno = '" . $order_no . "'", $edit);
            $data['is_vip'] = 1;
            if ($user_data['p_id'] !== 0) {
                $price['balance'] = 99 * 0.6;
                $this->model->change('sy_user', $user_data['p_id'], $price);
            }
            $this->model->change('sy_user', $uid, $data);
            $signed = new Signed();
            $signed->_data('', 99, 0);
            return $this->redirect('/myself');
        }
    }

    /**
     * @var 生成链接
     */
    public function createCut()
    {
        $arr['cut_pid'] = input('get.pid') ? input('get.pid') : 0;
        $arr['cut_uid'] = $this->uid;
        $arr['cut_cid'] = $this->uid;
        if ($arr['cut_pid']) {
            // 应该做砍价校验
            $startTime = strtotime(date('Y-m-d', time())) - 7 * 24 * 60 * 60;
            $oid = (new CutDownModel(substr($this->uid, -1, 1)))->getValue("cut_pid = {$arr['cut_pid']} and cut_uid = {$this->uid} and cut_oid = 0 and create_time >= {$startTime}", 'cut_id');
            if (!$oid) {
                $arr['create_time'] = time();
                $result = (new CutDownModel(substr($this->uid, -1, 1)))->insertOne($arr);
                $data['code'] = 200;
                $data['data'] = [
                    'uid' => $this->uid,
                    'oid' => $result ? $result : 0
                ];
            } else {
                $data['code'] = 202;
                $data['info'] = '你已经有该商品的砍价链接了';
                $data['data'] = [
                    'uid' => $this->uid,
                    'oid' => $oid
                ];
            }

        }
        return json_encode($data);
    }


    public function cutdown($limit)
    {
        $time = time() - 60 * 60 * 24 * 7;
        $list = (new CutDownModel(substr($this->uid, -1, 1), 'id desc', (int)$limit, 'sy_product_info pi', 'pi.id = ct.cut_pid', '', 'ct'))->selectAll("ct.cut_uid = {$this->uid} and ct.create_time >= {$time}", '');
        if ($limit) {
            return json_encode($list);
        }
        $this->assign('list', $list);
        $this->assign('uid', $this->uid);
        return $this->fetch();
    }

    //清空缓存
	public function clear()
	{
		echo '<pre>';
		foreach ($_COOKIE as $key => $value) {
			Cookie::set($key,'',-1);
		}
		session(null);
		echo "<script>alert('清楚缓存成功!');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
	}

}
